// server.js

const express = require('express');
const cors = require('cors');
const config = require('./config');
const rateLimitMiddleware = require('./middleware/rateLimit');
const dataRoutes = require('./routes/data');
const uploadRoutes = require('./routes/upload');

const app = express();

// Middleware
app.use(cors());
app.use(express.json());
app.use(rateLimitMiddleware);

// Routes
app.use('/api', dataRoutes);
app.use('/api', uploadRoutes);

// Error handling middleware
app.use((err, req, res, next) => {
  if (err.name === 'MulterError') {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(200).json({
        code: '0',
        data: {},
        msg: 'File size exceeds the limit of 20MB'
      });
    }
  }
  
  if (err.message === 'Only .apk files are allowed') {
    return res.status(200).json({
      code: '0',
      data: {},
      msg: 'Invalid file type. Only .apk files are allowed'
    });
  }

  console.error('Unhandled error:', err);
  res.status(200).json({
    code: '-1',
    data: {},
    msg: 'Internal server error'
  });
});

// Start server
app.listen(config.server.port, () => {
  console.log(`Server is running on port ${config.server.port}`);
});
